package cn.itcast.test;


import cn.itcast.domain.Customer;
import cn.itcast.utils.JpaUtils;
import org.junit.Test;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

/*优化Test*/
public class JpaTest2 {

    /*添加用户*/
    @Test
    public void test(){
        //读取persistence.xml中定义的单元
        EntityManager em = JpaUtils.getEntityManager();
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        Customer customer = new Customer();
        customer.setCustName("路线经");

        //自动创建表
        em.persist(customer); //保存操作
        tx.commit();
        em.close();
    }



    /*根据id查询用户
    * 使用find方法查询   立即加载*/
    @Test
    public void testFind(){
        EntityManager em = JpaUtils.getEntityManager();
        EntityTransaction tx = em.getTransaction();
        tx.begin();

        //根据id查询数据
        //查询的数据封装的类型  Customer.class
        //查询的主键值
        Customer customer = em.find(Customer.class,1l);
        System.out.println(customer);

        tx.commit();
        em.close();
    }

    /*根据id查询用户
    * getReference  延迟加载  得到一个动态代理对象  当调用查询结果的时候才会真正发送sql语句查询数据库*/
    @Test
    public void testReference(){
        EntityManager em = JpaUtils.getEntityManager();
        EntityTransaction tx = em.getTransaction();
        tx.begin();

        //根据id查询数据
        //查询的数据封装的类型  Customer.class
        //查询的主键值
        Customer customer = em.getReference(Customer.class,1l);
        System.out.println(customer);

        tx.commit();
        em.close();
    }



    /*删除用户*/
    @Test
    public void testRemove(){
        EntityManager em = JpaUtils.getEntityManager();
        EntityTransaction tx = em.getTransaction();
        tx.begin();

        Customer customer = em.find(Customer.class,1l);

        //删除客户
         em.remove(customer);

        System.out.println(customer);

        tx.commit();
        em.close();
    }


    /*修改用户*/
    @Test
    public void testUpdate(){
        EntityManager em = JpaUtils.getEntityManager();
        EntityTransaction tx = em.getTransaction();
        tx.begin();

        //先查询客户
        Customer customer = em.find(Customer.class,2l);
        customer.setCustName("鲁大师");

        //修改
        em.merge(customer);

        System.out.println(customer);

        tx.commit();
        em.close();
    }
}

